/**
 * @file       file_lock.cpp
 * @brief      
 * @author     LiuJkun
 * @version    1.0.0
 */

/*********************************************************************
 *  LiuJikun   01/16/10      Initial Version
 *********************************************************************/

#include	<stdlib.h>
#include    <stdio.h>
#include	<sys/stat.h>
#include	<fcntl.h>
#include	<unistd.h>
#include	<string.h>
#include	<stdint.h>
#include	<errno.h>

/**
 * @brief 
 */
void lock_read ( int fd, off_t offset, off_t len )
{
    struct flock lock;
    memset( &lock, 0, sizeof(lock) );
    printf ( "lock_read...\n" );
    lock.l_type = F_RDLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 3;
    printf ( "before read lock\n" );
    int32_t res = fcntl( fd, F_SETLKW, &lock );
    if ( -1 == res ) {
        perror("read lock:");
    }
    printf ( "after read lock\n" );
    return ;
}	
/**
 * @brief 
 */
void lock_write ( int fd, off_t offset, off_t len )
{
    struct flock lock;
    memset( &lock, 0, sizeof(lock) );
    printf ( "lock_write\n" );
    lock.l_type = F_WRLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 3;
    printf ( "before write lock\n" );
    int32_t res = fcntl( fd, F_SETLKW, &lock );
    if ( -1 == res ) {
        printf ( "errno = %d\n", errno );
        perror("write lock");
    }
    printf ( "after write lock\n" );
    return ;
}	
/**
 * @brief 
 */
void unlock_file ( int fd, off_t offset, off_t len )
{
    struct flock lock;
    memset( &lock, 0, sizeof(lock) );
    printf ( "unlock_file\n" );
    lock.l_type = F_WRLCK;
    lock.l_whence = SEEK_SET;
    lock.l_start = 0;
    lock.l_len = 3;
    printf ( "before unlock\n" );
    int32_t res = fcntl( fd, F_SETLK, &lock );
    if ( -1 == res ) {
        printf ( "errno = %d\n", errno );
        perror("unlock");
    }
    printf ( "after unlock\n" );
    return ;
}	
